package com.ruoyi.site.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.site.domain.*;
import com.ruoyi.site.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.site.mapper.OrderDetailsMapper;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

/**
 * 订单详情Service业务层处理
 * 
 * @author chuckeytang
 * @date 2025-08-17
 */
@Service
public class OrderDetailsServiceImpl implements IOrderDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(OrderDetailsServiceImpl.class);
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Autowired
    private IOrderItemsService orderItemsService;

    @Autowired
    private ICartsService cartsService;

    @Autowired
    private ICartItemsService cartItemsService;

    @Autowired
    private ITracksService tracksService;

    @Autowired
    private ISfxService sfxService;

    @Autowired
    private IUserLicensesService userLicensesService;

    /**
     * 查询订单详情
     * 
     * @param orderId 订单详情主键
     * @return 订单详情
     */
    @Override
    public OrderDetails selectOrderDetailsByOrderId(Long orderId)
    {
        return orderDetailsMapper.selectOrderDetailsByOrderId(orderId);
    }

    /**
     * 查询订单详情列表
     * 
     * @param orderDetails 订单详情
     * @return 订单详情
     */
    @Override
    public List<OrderDetails> selectOrderDetailsList(OrderDetails orderDetails)
    {
        return orderDetailsMapper.selectOrderDetailsList(orderDetails);
    }

    /**
     * 新增订单详情
     * 
     * @param orderDetails 订单详情
     * @return 结果
     */
    @Override
    public int insertOrderDetails(OrderDetails orderDetails)
    {
        return orderDetailsMapper.insertOrderDetails(orderDetails);
    }

    /**
     * 修改订单详情
     * 
     * @param orderDetails 订单详情
     * @return 结果
     */
    @Override
    public int updateOrderDetails(OrderDetails orderDetails)
    {
        return orderDetailsMapper.updateOrderDetails(orderDetails);
    }

    /**
     * 批量删除订单详情
     * 
     * @param orderIds 需要删除的订单详情主键
     * @return 结果
     */
    @Override
    public int deleteOrderDetailsByOrderIds(Long[] orderIds)
    {
        return orderDetailsMapper.deleteOrderDetailsByOrderIds(orderIds);
    }

    /**
     * 删除订单详情信息
     * 
     * @param orderId 订单详情主键
     * @return 结果
     */
    @Override
    public int deleteOrderDetailsByOrderId(Long orderId)
    {
        return orderDetailsMapper.deleteOrderDetailsByOrderId(orderId);
    }

    /**
     * 根据用户ID查询订单详情列表 (前台用户查看)
     */
    @Override
    public List<OrderDetails> selectOrderDetailsListByUserId(Long userId) {
        return orderDetailsMapper.selectOrderDetailsListByUserId(userId);
    }

    /**
     * 从购物车创建订单
     * 必须是事务性的！
     */
    @Override
    @Transactional
    public OrderDetails createOrderFromCart(Long userId) {
        // 1. 获取用户的购物车（及其项目）
        Carts cart = cartsService.selectCartsByUserId(userId);
        if (cart == null || cart.getItems() == null || cart.getItems().isEmpty()) {
            throw new ServiceException("购物车为空，无法创建订单");
        }

        // 2. 计算总价
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CartItems item : cart.getItems()) {
            // 确保价格不为空，且数量大于0
            if (item.getPriceAtAddition() != null && item.getQuantity() > 0) {
                totalAmount = totalAmount.add(item.getPriceAtAddition().multiply(new BigDecimal(item.getQuantity())));
            }
        }

        // 3. 创建订单头 (OrderDetails)
        OrderDetails order = new OrderDetails();
        order.setUserId(userId);
        order.setStatus("PENDING_PAYMENT"); // 初始状态：待支付
        order.setCurrency("USD");
        order.setTotalAmount(totalAmount);
        order.setCreatedAt(new Date());
        order.setUpdatedAt(new Date());
        orderDetailsMapper.insertOrderDetails(order); // 插入后，orderId 会被 Mybatis 回填

        // 4. 转换购物车项目为订单项目 (OrderItems)
        for (CartItems cartItem : cart.getItems()) {
            OrderItems orderItem = new OrderItems();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setProductType(cartItem.getProductType());
            orderItem.setLicenseOption(cartItem.getLicenseOption());

            String licenseOption = cartItem.getLicenseOption();
            if (licenseOption == null || licenseOption.trim().isEmpty()) {
                licenseOption = "Standard";
            }
            orderItem.setLicenseOption(licenseOption);

            // 根据产品类型设置ID
            if ("track".equalsIgnoreCase(cartItem.getProductType())) {
                orderItem.setTrackId(cartItem.getProductId());
            } else if ("sfx".equalsIgnoreCase(cartItem.getProductType())) {
                orderItem.setSfxId(cartItem.getProductId());
            }
            // (如果还有 plan 类型...)

            orderItem.setPurchasePrice(cartItem.getPriceAtAddition());
            // (注意：这里没有处理 quantity，因为音乐购买通常 quantity=1。如果您的业务支持购买多份，OrderItems 也需要 quantity 字段)

            orderItemsService.insertOrderItems(orderItem);
        }

        // 5. 清空购物车
        cartItemsService.deleteCartItemsByCartId(cart.getCartId());

        return order;
    }

    @Override
    public boolean checkUserHasPurchasedTrack(Long userId, Long trackId) {
        int count = orderDetailsMapper.countPaidPurchases(userId, trackId);
        return count > 0;
    }

    /**
     * 获取产品价格 (复用或简化之前的逻辑)
     */
    private BigDecimal getProductPrice(String productType, Long productId, String licenseOption) {
        // 假设 ITracksService 和 ISfxService 已实现获取标准价格的方法
        if ("track".equalsIgnoreCase(productType)) {
            return tracksService.getStandardPriceByTrackId(productId);
        } else if ("sfx".equalsIgnoreCase(productType)) {
            return sfxService.getStandardPriceBySfxId(productId);
        }
        return BigDecimal.ZERO;
    }

    @Override
    @Transactional
    public OrderDetails createOrderForSingleItem(Long userId, String productType, Long productId, String licenseOption) {

        if (licenseOption == null || licenseOption.trim().isEmpty()) {
            licenseOption = "Standard";
            log.warn("createOrderForSingleItem 接收到空的 licenseOption，已默认设置为: {}", licenseOption);
        }

        // 1. 获取产品价格
        BigDecimal price = getProductPrice(productType, productId, licenseOption);

        if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("无法获取产品价格或价格无效。");
        }

        // 2. 创建订单头 (OrderDetails)
        OrderDetails order = new OrderDetails();
        order.setUserId(userId);
        order.setStatus("PENDING_PAYMENT"); // 初始状态：待支付
        order.setCurrency("USD");
        order.setTotalAmount(price);       // 总价即为单价
        order.setCreatedAt(new Date());
        order.setUpdatedAt(new Date());
        // 假设 orderDetailsMapper.insertOrderDetails(order) 会回填 orderId
        orderDetailsMapper.insertOrderDetails(order);

        // 3. 创建订单项 (OrderItems)
        OrderItems orderItem = new OrderItems();
        orderItem.setOrderId(order.getOrderId());
        orderItem.setProductType(productType);
        orderItem.setLicenseOption(licenseOption);
        orderItem.setPurchasePrice(price);
        orderItem.setLicenseOption(licenseOption);

        if ("track".equalsIgnoreCase(productType)) {
            orderItem.setTrackId(productId);
        } else if ("sfx".equalsIgnoreCase(productType)) {
            orderItem.setSfxId(productId);
        }

        // 假设 orderItemsService.insertOrderItems(orderItem) 已存在
        orderItemsService.insertOrderItems(orderItem);

        return order;
    }

    @Override
    @Transactional
    public void grantLicensesForOrder(Long orderId) {
        // 1. 获取订单详情和订单项
        OrderDetails order = orderDetailsMapper.selectOrderDetailsByOrderId(orderId); // 假设此方法会联查 items 或我们单独查

        OrderItems queryItems = new OrderItems();
        queryItems.setOrderId(orderId);
        List<OrderItems> items = orderItemsService.selectOrderItemsList(queryItems); // 假设 OrderItemsService 能查出列表

        // 2. 遍历订单项，创建 UserLicenses 记录
        for (OrderItems item : items) {
            if ("track".equals(item.getProductType()) || "sfx".equals(item.getProductType())) {

                UserLicenses license = new UserLicenses();
                license.setUserId(order.getUserId());
                license.setOrderId(orderId);
                license.setProductType(item.getProductType());
                license.setProductId(item.getTrackId() != null ? item.getTrackId() : item.getSfxId());

                String licenseOption = item.getLicenseOption();

                if (licenseOption == null || licenseOption.trim().isEmpty()) {
                    licenseOption = "Standard";
                    log.error("在授权时发现 OrderItem {} 的 license_option 为空，已默认设置为: {}", item.getOrderItemId(), licenseOption);
                }

                license.setLicenseOption(licenseOption);

                license.setPurchaseDate(new Date());
                license.setDownloadCount(0);

                // 3. 持久化授权
                userLicensesService.insertUserLicenses(license);
                log.debug("Granted {} license for product ID {}", license.getLicenseOption(), license.getProductId());
            }
        }
    }
}
